<template>
    <div>
        <div class="search-field">
            <div class="input-group">
                <!-- Select Dropdown -->
                <select class="form-select" v-model="selectedOption">
                    <option selected>选择搜索方式</option>
                    <option value="InvoiceNum">按发票编号</option>
                    <option value="PurchaserName">按购买方名称</option>
                    <option value="AmountInFiguers">按价税合计</option>
                    <option value="InvoiceDate">按开票日期</option>
                    <option value="createtime">按上传日期</option>
                </select>

                <select class="form-matching" v-model="selectedMatching">
                    <option value="exactMatching">完全匹配</option>
                    <option value="fuzzyMatching">模糊匹配</option>
                </select>
                
                <!-- Search Input -->
                <input 
                    class="form-control" 
                    type="search" 
                    :placeholder="placeholder" 
                    aria-label="Search" 
                    v-model="searchQuery"
                />
                
                <!-- Search Button -->
                <button class="btn btn-outline-secondary search-button" type="button" @click="handleSearch">搜索</button>
            </div>
        </div>

        <p v-if="!is_success" style="margin-top: 5px; color: red; text-align: center;">{{ error_message }}</p>

        <div style="margin-top: 30px;" v-if="records.length != 0">
            <table class="table table-hover" style="text-align: center; vertical-align: middle;">
                <thead>
                    <tr>
                        <th>发票编号</th>
                        <th>购买方名称</th>
                        <th>价税合计</th>
                        <th>开票日期</th>
                        <th>上传日期</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="record in records" :key="record.id">
                        <td>{{ record.invoiceNum }}</td>
                        <td>{{ record.purchaserName }}</td>
                        <td>{{ record.amountInFiguers }}</td>
                        <td>{{ record.invoiceDate }}</td>
                        <td>{{ record.createtime }}</td>
                        <td>
                            <button type="button" class="btn btn-outline-secondary btn-sm" @click="clickToDetails(record)">查看详情</button>
                            <button type="button" class="btn btn-outline-danger btn-sm" style="margin-left: 10px;">废弃</button>
                        </td>
                    </tr>
                </tbody>
            </table>
            <nav aria-label="..." v-if="records.length != 0">
                <ul class="pagination" style="float: right;">
                    <li class="page-item" @click="click_page(-2)">
                        <a class="page-link" href="#">前一页</a>
                    </li>
                    <li :class="'page-item ' + page.is_active" v-for="page in pages" :key="page.number" @click="click_page(page.number)">
                        <a class="page-link" href="#">{{ page.number }}</a>
                    </li>
                    <li class="page-item" @click="click_page(-1)">
                        <a class="page-link" href="#">后一页</a>
                    </li>
                </ul>
            </nav>
        </div>
    </div>
</template>

<script setup>
import $ from 'jquery';
import { useStore } from 'vuex';
import { ref } from 'vue';
import router from '@/router/index';
import { computed } from 'vue';

const store = useStore();
let records = ref([]);
let current_page = 1;
let total_records = 0;
let pages = ref([]);

const selectedOption = ref('选择搜索方式');  // 选择框的绑定值
const selectedMatching = ref("exactMatching");  //  选择匹配方式
const searchQuery = ref(null);           // 搜索框的绑定值
const error_message = ref(null);
const is_success = ref(null);
const placeholder = computed(() => {
    if (selectedMatching.value == "exactMatching") {
        if (selectedOption.value == "InvoiceNum") {
            return "请输入发票编号";
        } else if (selectedOption.value == "PurchaserName") {
            return "请输入购买方名称";
        } else if (selectedOption.value == "AmountInFiguers") {
            return "请输入价税合计金额，如：367.50（保留两位小数）";
        } else if (selectedOption.value == "InvoiceDate") {
            return "请输入开票日期，如：2018年02月02日";
        } else if (selectedOption.value == "createtime") {
            return "请输入上传日期，如：2024-11-18";
        }
    }
    else {
        if (selectedOption.value == "InvoiceNum") {
            return "请输入发票编号";
        } else if (selectedOption.value == "PurchaserName") {
            return "请输入购买方名称";
        } else if (selectedOption.value == "AmountInFiguers") {
            return "请输入价税合计金额";
        } else if (selectedOption.value == "InvoiceDate") {
            return "请输入开票日期";
        } else if (selectedOption.value == "createtime") {
            return "请输入上传日期（年月日之间用'-'分隔）";
        }
    }
    
    return "请输入";  // 默认提示
});

const click_page = page => {
    if (page === -2) page = current_page - 1;
    else if (page === -1) page = current_page + 1;
    
    let max_pages = parseInt(Math.ceil(total_records / 10))
    if (page >= 1 && page <= max_pages) {
        pull_page(page);
    }
}

const update_pages = () => {
    let max_pages = parseInt(Math.ceil(total_records / 10))
    let new_pages = [];
    for (let i = current_page - 2; i <= current_page + 2; i ++) {
        if (i >= 1 && i <= max_pages) {
            new_pages.push({
                number: i,
                is_active: i === current_page ? "active" : "",
            });
        }
    }
    pages.value = new_pages;
}

const clearMessage = () => {
    is_success.value = null;
    error_message.value = null;
}

const pull_page = page => {
    current_page = page;
    $.ajax({
        url: "http://localhost:3000/api/invoice/search-result",
        type: "get",
        data: {
            selectedOption: selectedOption.value,
            selectedMatching: selectedMatching.value,
            searchQuery: searchQuery.value,
            selectedObject: "own",
            page,
        },
        headers: {
            Authorization: "Bearer " + store.state.user.token,
        },
        success(resp) {
            if (resp.error_message == "success") {
                is_success.value = true;
                records.value = resp.records;
                total_records = resp.records_count;
                update_pages();
                store.commit("updateRecords", resp.records);
            } else if (resp.error_message != "error") {
                is_success.value = false;
                error_message.value = resp.error_message;
                setTimeout(clearMessage, 5000);
            }
        },
        error(resp) {
            console.log(resp);
        }
    })
}

const clickToDetails = record => {
    router.push({
        name: "InvoiceDetails",
        params: {
            id: record.id
        },
    })
}

// 处理搜索逻辑
const handleSearch = () => {
    pull_page(current_page);
}

</script>

<style scoped>

.search-field {
    width: 100%;            /* 让search-field宽度填满父容器 */
    display: flex;
    justify-content: center;  /* 水平居中 */
    margin-top: 10px;
}

.input-group {
    width: 70%;             /* 设置input-group占容器的70% */
    display: flex;
    gap: 10px;
}

.form-select {
    flex: 2;
    border: 2px solid #6c757d;  /* 边框宽度和颜色 */
    border-radius: 4px;        /* 圆角 */
    padding: 0.375rem 0.75rem; /* 内边距 */
}

.form-matching {
    flex: 1;
    border: 2px solid #6c757d;  /* 边框宽度和颜色 */
    border-radius: 4px;        /* 圆角 */
    padding: 0.375rem 0.75rem; /* 内边距 */
}

.form-control {
    flex: 8;
    border: 2px solid #6c757d;  /* 边框宽度和颜色 */
    border-radius: 4px;        /* 圆角 */
    padding: 0.375rem 0.75rem; /* 内边距 */
}

.search-button {
    flex-shrink: 0; /* 按钮宽度固定 */
    border: 2px solid #6c757d;  /* 边框宽度和颜色 */
    border-radius: 4px;        /* 圆角 */
    padding: 0.375rem 0.75rem; /* 内边距 */
}

</style>